package study

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var rwLock sync.RWMutex

func testRWLock() {
	var a map[int]int
	a = make(map[int]int, 5)
	a[8] = 10
	a[3] = 10
	a[2] = 10
	a[1] = 10
	a[18] = 10
	for i := 0; i < 2; i++ {
		go func(b map[int]int) {
			rwLock.Lock()
			b[8] = rand.Intn(100)
			rwLock.Unlock()
		}(a)
	}
	for i := 0; i < 10; i++ {
		go func(b map[int]int) {
			rwLock.RLock() //读锁
			fmt.Println(a)
			rwLock.RUnlock()
		}(a)
	}
	time.Sleep(time.Second * 2)

}
func mutexTest() {
	//声明
	var mutex sync.Mutex
	fmt.Println("Lock the lock. (G0)")
	//加锁mutex
	mutex.Lock()

	fmt.Println("The lock is locked.(G0)")
	for i := 1; i < 4; i++ {
		go func(i int) {
			fmt.Printf("Lock the lock.(G%d)\r\n", i)
			mutex.Lock()
			fmt.Printf("The lock is locked.(G%d)\r\n", i)
		}(i)
	}
	time.Sleep(time.Second)
	fmt.Println("Unlock the lock. (G0)")
	//解锁mutex
	mutex.Unlock()

	fmt.Println("The lock is unlocked. (G0)")
	time.Sleep(time.Second)

}
